/*
 * @(#)TestsetTranslator.java
 *
 *
 *
 * ver 1.0 Sep 4, 2007 ggranum
 */
package org.testfire.realm.view.json.translator;

import org.json.JSONException;
import org.json.JSONObject;
import org.testfire.realm.model.entities.testfire.TestsetEntity;
import org.testfire.realm.view.tags.util.JavaScriptUtilities;
import org.testfire.realm.util.json.JsonField;
import org.testfire.realm.util.json.Tools;

import java.sql.Timestamp;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * Application Scope
 *
 */
public class TestsetTranslator implements JsonTranslator<TestsetEntity>
{

	static final List<JsonField> ALL_FIELDS = new ArrayList<JsonField>();

	static
	{
		ALL_FIELDS.add(new JsonField("id", JsonField.TYPE_INT));
		ALL_FIELDS.add(new JsonField("name", JsonField.TYPE_STRING));
		ALL_FIELDS.add(new JsonField("description", JsonField.TYPE_STRING));
		ALL_FIELDS.add(new JsonField("username", JsonField.TYPE_STRING));
		ALL_FIELDS.add(new JsonField("created", JsonField.TYPE_DATE));
		ALL_FIELDS.add(new JsonField("lastverified", JsonField.TYPE_DATE));
		ALL_FIELDS.add(new JsonField("forbug", JsonField.TYPE_STRING));
	}

	public String toJson(TestsetEntity object)
	{
		return Tools.getJsonString(object, ALL_FIELDS);
	}

	public String toJson(TestsetEntity object, String fields) throws JSONException
	{
		return Tools.getJsonString(object, fields);
	}

	public String toJson(List<TestsetEntity> objects)
	{
		return Tools.getJsonString(objects, ALL_FIELDS);
	}

	public String toJsonArray(List<TestsetEntity> objects, String fields) throws JSONException
	{
		return Tools.getJsonString(objects, fields);
	}

	public TestsetEntity toObject(String json) throws JSONException
	{
		JSONObject obj = new JSONObject(json);
		TestsetEntity testset = new TestsetEntity();
		int id = (Integer) obj.get("id");
		Date created;
		Date lastVerified;		
		try
		{
			created = JavaScriptUtilities.toDateTime((String) obj.get("created"));
			lastVerified = JavaScriptUtilities.toDateTime((String) obj.get("lastverified"));
		}
		catch (ParseException e)
		{
			throw new RuntimeException(e);

		}
		testset.setId(id);
		testset.setCreated(new Timestamp(created.getTime()));
		testset.setLastverified(new Timestamp(lastVerified.getTime()));
		testset.setForbug((String) obj.get("forbug"));
		testset.setDescription((String) obj.get("description"));
		testset.setName((String) obj.get("name"));
		return testset;
	}

	public TestsetEntity copyValues(TestsetEntity to, TestsetEntity from){
		to.setCreated(from.getCreated());
		to.setDescription(from.getDescription());
		to.setForbug(from.getForbug());
		// don't set id
		to.setLastverified(from.getLastverified());
		to.setName(from.getName());
		// all other setters are for collections, not directly editable by user.
		return to;
	}


}

// eof: TestsetTranslator.java